package com.example.concurrent.demo.threads;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 使用Callable和Future创建线程
 * @author liu.nh
 */
@Slf4j
public class CreateThreadByCallable implements Callable<Integer> {

    @Override
    public Integer call() {
        int i = 0;
        for (; i < 10; i++) {
            log.info(Thread.currentThread().getName() + " " + i);
        }
        return i;
    }

    public static void main(String[] args) {
        CreateThreadByCallable myThread = new CreateThreadByCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(myThread);
        for (int i = 0; i < 10; i++) {
            log.info(Thread.currentThread().getName() + " 的循环变量i的值" + i);
            if (i == 6) {
                new Thread(futureTask, "有返回值的线程").start();
            }
        }
        try {
            log.info("子线程的返回值：" + futureTask.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
